package com.cn.web.controller.Equipment;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cn.bean.pojo.PartsManagement.BusinessTypeTable;
import com.cn.bean.pojo.mc.McHcList;
import com.cn.bean.vo.Equipment.*;
import com.cn.config.config.Result;
import com.cn.service.server.Equipment.EquipmentStructureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/Equ")
@Transactional
public class EquipmentStructureController {
    private final EquipmentStructureService equipmentStructureService;

    @Autowired(required = false)
    public EquipmentStructureController(EquipmentStructureService equipmentStructureService) {
        this.equipmentStructureService = equipmentStructureService;

    }

    @RequestMapping("/select/EquipmentStructureChild/All")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentStructureChildAll(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("ID");
        List<EquipmentStructure> equipmentStructures = equipmentStructureService.selectEquipmentStructureChildAll(id);
        Map<Integer, EquipmentStructure> nodeMap = new HashMap<>();
        for (EquipmentStructure nodeData : equipmentStructures) {
            EquipmentStructure node = new EquipmentStructure();
            node.setCID(nodeData.getCID());
            node.setLevel(nodeData.getLevel());
            node.setParentID(nodeData.getParentID());
            node.setCategoryID(nodeData.getCategoryID());
            node.setCategoryName(nodeData.getCategoryName());
            node.setComponentID(nodeData.getComponentID());
            node.setComponentName(nodeData.getComponentName());
            node.setIsSplit(nodeData.getIsSplit());
            node.setIsSplitLeftRight(nodeData.getIsSplitLeftRight());
            node.setMeasurementUnit(nodeData.getMeasurementUnit());
            node.setQuantity(nodeData.getQuantity());
            node.setReplacementCycleMethod(nodeData.getReplacementCycleMethod());
            node.setCycleDays(nodeData.getCycleDays());
            node.setReplacementCycleDailyOutput(nodeData.getReplacementCycleDailyOutput());
            node.setPartAttributes(nodeData.getPartAttributes());
            node.setUpperCount(nodeData.getUpperCount());
            nodeMap.put(node.getCID(), node);
        }
        for (EquipmentStructure nodeData : equipmentStructures) {
            EquipmentStructure node = nodeMap.get(nodeData.getCID());
            if (node.getParentID() != 0) {
                EquipmentStructure parent = nodeMap.get(node.getParentID());
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        List<EquipmentStructure> roots = new ArrayList<>();
        for (EquipmentStructure node : nodeMap.values()) {
            if (node.getParentID() == 0) {
                roots.add(node);
            }
        }
        return roots;
    }

    //   修改
    @RequestMapping("/update/Equipment/Structure")
    @ResponseBody
    public Result upDateEquipmentStructure(@RequestBody JSONObject jsonObject) {
        EquipmentStructure formMainTable = jsonObject.getObject("formMainTable", EquipmentStructure.class);
        JSONArray tableData1 = jsonObject.getJSONArray("tableDate1Lsit");
        JSONArray tableDate2 = jsonObject.getJSONArray("tableDate2Lsit");
        JSONArray tableDate3 = jsonObject.getJSONArray("tableDate3Lsit");

        List<ComponentBasicInformation> tableData3List = new ArrayList<>();
        for (int i = 0; i < tableDate3.size(); i++) {
            JSONObject jsonObject3 = tableDate3.getJSONObject(i);
            ComponentBasicInformation childStructure = jsonObject3.toJavaObject(ComponentBasicInformation.class);
            tableData3List.add(childStructure);

        }
        List<EquipmentComponentMaterialMappingSetting> tableData2List = new ArrayList<>();
        for (int i = 0; i < tableDate2.size(); i++) {
            JSONObject jsonObject2 = tableDate2.getJSONObject(i);
            EquipmentComponentMaterialMappingSetting childStructure = jsonObject2.toJavaObject(EquipmentComponentMaterialMappingSetting.class);
            tableData2List.add(childStructure);

        }
        List<ComponentStructureGroupComposition> tableData1List = new ArrayList<>();
        if (tableData1.size() == 0) {
            for (int i = 0; i < formMainTable.getQuantity(); i++) {
                ComponentStructureGroupComposition componentStructureGroupComposition = new ComponentStructureGroupComposition();
                componentStructureGroupComposition.setGroupNumber("无");
                componentStructureGroupComposition.setUniversalBetweenGroups(1);
                componentStructureGroupComposition.setQuantityWithinGroup(1);
                tableData1List.add(componentStructureGroupComposition);

            }
        } else {
            for (int i = 0; i < tableData1.size(); i++) {
                JSONObject jsonObject1 = tableData1.getJSONObject(i);
                ComponentStructureGroupComposition childStructure = jsonObject1.toJavaObject(ComponentStructureGroupComposition.class);
                tableData1List.add(childStructure);
            }

        }
        return equipmentStructureService.upDateEquipmentStructure(formMainTable, tableData1List, tableData2List, tableData3List);


    }

    //添加子表和子子表
    @RequestMapping("/add/EquipmentStructure/ChileChild")
    @ResponseBody
    public Result addEquipmentStructureChileChild(@RequestBody JSONObject jsonObject) {
        EquipmentStructure formMainTable = jsonObject.getObject("formMainTable", EquipmentStructure.class);
        JSONArray tableData1 = jsonObject.getJSONArray("tableDate1Lsit");
        JSONArray tableDate2 = jsonObject.getJSONArray("tableDate2Lsit");
        JSONArray tableDate3 = jsonObject.getJSONArray("tableDate3Lsit");

        List<ComponentBasicInformation> tableData3List = new ArrayList<>();
        for (int i = 0; i < tableDate3.size(); i++) {
            JSONObject jsonObject3 = tableDate3.getJSONObject(i);
            ComponentBasicInformation childStructure = jsonObject3.toJavaObject(ComponentBasicInformation.class);
            tableData3List.add(childStructure);

        }
        List<EquipmentComponentMaterialMappingSetting> tableData2List = new ArrayList<>();
        for (int i = 0; i < tableDate2.size(); i++) {
            JSONObject jsonObject2 = tableDate2.getJSONObject(i);
            EquipmentComponentMaterialMappingSetting childStructure = jsonObject2.toJavaObject(EquipmentComponentMaterialMappingSetting.class);
            tableData2List.add(childStructure);

        }
        List<ComponentStructureGroupComposition> tableData1List = new ArrayList<>();
        if (tableData1.size() == 0) {
            for (int i = 0; i < formMainTable.getQuantity(); i++) {
                ComponentStructureGroupComposition componentStructureGroupComposition = new ComponentStructureGroupComposition();
                componentStructureGroupComposition.setGroupNumber("无");
                componentStructureGroupComposition.setUniversalBetweenGroups(1);
                componentStructureGroupComposition.setQuantityWithinGroup(1);
                tableData1List.add(componentStructureGroupComposition);

            }
        } else {
            for (int i = 0; i < tableData1.size(); i++) {
                JSONObject jsonObject1 = tableData1.getJSONObject(i);
                ComponentStructureGroupComposition childStructure = jsonObject1.toJavaObject(ComponentStructureGroupComposition.class);
                tableData1List.add(childStructure);
            }

        }
        return equipmentStructureService.addEquipmentStructureChileChild(formMainTable, tableData1List, tableData2List, tableData3List);
    }
    @RequestMapping("/select/EquipmentStructure/Main/Auto1")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentStructureMainAuto1(@RequestBody JSONObject jsonObject) {

        return equipmentStructureService.selectEquipmentStructureMainAuto1();
    }
    @RequestMapping("/select/EquipmentStructure")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentStructure(@RequestBody JSONObject jsonObject) {
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        String structureCode = jsonObject.getString("structureCode");
        String structureName = jsonObject.getString("structureName");
        structureCode = (structureCode != null) ? structureCode : "";
        structureName = (structureName != null) ? structureName : "";
        return equipmentStructureService.selectEquipmentStructure(limit, page, structureCode, structureName);
    }

    @RequestMapping("/select/EquipmentStructureID")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentStructureID(@RequestBody JSONObject jsonObject) {
        Integer businessTypeID = jsonObject.getInteger("businessTypeID");
        String structureName = jsonObject.getString("structureName");
        Integer versionStatus = jsonObject.getInteger("versionStatus");
        String description = jsonObject.getString("description");
        return equipmentStructureService.selectEquipmentStructureID(businessTypeID, structureName, versionStatus, description);
    }

    @RequestMapping("/add/EquipmentStructure")
    @ResponseBody
    public Result addEquipmentStructure(@RequestBody JSONObject jsonObject) {
//        Integer ID = jsonObject.getInteger("ID");
        Integer businessTypeID = jsonObject.getInteger("businessTypeID");
        String structureName = jsonObject.getString("structureName");
        Integer versionStatus = jsonObject.getInteger("versionStatus");
        String description = jsonObject.getString("description");
        Integer categoryID = jsonObject.getInteger("categoryID") != null ? jsonObject.getInteger("categoryID") : 0;
        Integer isSplit = jsonObject.getInteger("isSplit") != null ? jsonObject.getInteger("isSplit") : 0;
        Integer isSplitLeftRight = jsonObject.getInteger("isSplitLeftRight") != null ? jsonObject.getInteger("isSplitLeftRight") : 0;
        String replacementCycleMethod = jsonObject.getString("replacementCycleMethod");
        String cycleDays = jsonObject.getString("cycleDays");
        BigDecimal replacementCycleDailyOutput = jsonObject.getBigDecimal("replacementCycleDailyOutput");
        Integer partAttributes = jsonObject.getInteger("partAttributes") != null ? jsonObject.getInteger("partAttributes") : 0;
        Integer upperCount = jsonObject.getInteger("upperCount") != null ? jsonObject.getInteger("upperCount") : 0;
        Integer lowerCount = jsonObject.getInteger("lowerCount") != null ? jsonObject.getInteger("lowerCount") : 0;
        Integer leftCount = jsonObject.getInteger("leftCount") != null ? jsonObject.getInteger("leftCount") : 0;
        Integer rightCount = jsonObject.getInteger("rightCount") != null ? jsonObject.getInteger("rightCount") : 0;
        Integer upperLeftCount = jsonObject.getInteger("upperLeftCount") != null ? jsonObject.getInteger("upperLeftCount") : 0;
        Integer upperRightCount = jsonObject.getInteger("upperRightCount") != null ? jsonObject.getInteger("upperRightCount") : 0;
        Integer lowerLeftCount = jsonObject.getInteger("lowerLeftCount") != null ? jsonObject.getInteger("lowerLeftCount") : 0;
        Integer lowerRightCount = jsonObject.getInteger("lowerRightCount") != null ? jsonObject.getInteger("lowerRightCount") : 0;
        Integer quantity = jsonObject.getInteger("quantity") != null ? jsonObject.getInteger("quantity") : 0;
        String measurementUnit = jsonObject.getString("measurementUnit");
        return equipmentStructureService.addEquipmentStructure(businessTypeID, structureName, versionStatus, description, categoryID, isSplit, isSplitLeftRight, replacementCycleMethod, cycleDays, replacementCycleDailyOutput, partAttributes, upperCount, lowerCount, leftCount, rightCount, upperLeftCount, upperRightCount, lowerLeftCount, lowerRightCount, quantity, measurementUnit);
    }

    @RequestMapping("/delete/EquipmentStructure/ALL")
    @ResponseBody
    public Result deleteEquipmentStructureAll(@RequestBody JSONObject jsonObject) {
        JSONArray deleteIdList = jsonObject.getJSONArray("deleteIdList");
        List<EquipmentStructure> idList = new ArrayList<>();
        for (int i = 0; i < deleteIdList.size(); i++) {
            JSONObject deleteIdObject = deleteIdList.getJSONObject(i);
            int ID = deleteIdObject.getInteger("id");
            EquipmentStructure equipmentStructure = new EquipmentStructure();
            equipmentStructure.setID(ID);
            idList.add(equipmentStructure);
        }
        return equipmentStructureService.deleteEquipmentStructure(idList);
    }

    @RequestMapping("/delete/EquipmentStructure/ChileChild")
    @ResponseBody
    public Result deleteEquipmentStructureChileChild(@RequestBody JSONObject jsonObject) {
//        return Result.success("200","111");
        Integer cID = jsonObject.getInteger("cID");
        return equipmentStructureService.deleteEquipmentStructureChileChild(cID);
    }

    @RequestMapping("/select/Equipment/ComponeChildID")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentComponeChildID(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("ID");
        return equipmentStructureService.selectEquipmentComponeChildID(id);
    }

    @RequestMapping("/update/Equipment/EquipmentStructure/Main")
    @ResponseBody
    public Result updateEquipmentStructureMain(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("ID");
        Integer businessTypeID = jsonObject.getInteger("businessTypeID");
        String structureName = jsonObject.getString("structureName");
        Integer versionStatus = jsonObject.getInteger("versionStatus");
        String description = jsonObject.getString("description");
        String version = jsonObject.getString("version");

        return equipmentStructureService.updateEquipmentStructureMain(id, businessTypeID, structureName, versionStatus, version, description);
    }
//    @RequestMapping("/select/All/Main")
//    @ResponseBody
//    public List<EquipmentStructure> selectAllMain(@RequestBody JSONObject jsonObject) {
//        Integer id = jsonObject.getInteger("ID");
//        List<EquipmentStructure> equipmentStructures1 = equipmentStructureService.selectAllMain(id);
//        List<EquipmentStructure> equipmentStructures = equipmentStructureService.selectEquipmentStructureChildAll(id);
//
//        for (EquipmentStructure equipmentStructure : equipmentStructures1) {
//            equipmentStructure.setEqmList(equipmentStructures);
//        }
//        return equipmentStructures1;
//    }


    @RequestMapping("/select/All/Main")
    @ResponseBody
    public List<EquipmentStructure> selectAllMain(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("ID");
        List<EquipmentStructure> equipmentStructures1 = equipmentStructureService.selectAllMain(id);
        List<EquipmentStructure> equipmentStructures = equipmentStructureService.selectEquipmentStructureChildAll(id);
        Map<Integer, EquipmentStructure> nodeMap = new HashMap<>();
        for (EquipmentStructure nodeData : equipmentStructures) {
            EquipmentStructure node = new EquipmentStructure();
            node.setCID(nodeData.getCID());
            node.setLevel(nodeData.getLevel());
            node.setParentID(nodeData.getParentID());
            node.setCategoryID(nodeData.getCategoryID());
            node.setCategoryName(nodeData.getCategoryName());
            node.setComponentID(nodeData.getComponentID());
            node.setComponentName(nodeData.getComponentName());
            node.setIsSplit(nodeData.getIsSplit());
            node.setIsSplitLeftRight(nodeData.getIsSplitLeftRight());
            node.setMeasurementUnit(nodeData.getMeasurementUnit());
            node.setQuantity(nodeData.getQuantity());
            node.setReplacementCycleMethod(nodeData.getReplacementCycleMethod());
            node.setCycleDays(nodeData.getCycleDays());
            node.setReplacementCycleDailyOutput(nodeData.getReplacementCycleDailyOutput());
            node.setPartAttributes(nodeData.getPartAttributes());
            node.setUpperCount(nodeData.getUpperCount());
//            node.setCategoryName(nodeData.getCategoryName());
            nodeMap.put(node.getCID(), node);
        }
        for (EquipmentStructure nodeData : equipmentStructures) {
            EquipmentStructure node = nodeMap.get(nodeData.getCID());
            if (node.getParentID() != 0) {
                EquipmentStructure parent = nodeMap.get(node.getParentID());
                if (parent != null) {
                    parent.getChildren().add(node);
                }
            }
        }
        List<EquipmentStructure> roots = new ArrayList<>();
        for (EquipmentStructure node : nodeMap.values()) {
            if (node.getParentID() == 0) {
                roots.add(node);
            }
        }
        setIndex(roots, "");
        for (EquipmentStructure equipmentStructure : equipmentStructures1) {
            equipmentStructure.setEqmList(roots);
        }
        return equipmentStructures1;
    }

//    private EquipmentStructure findParent(EquipmentStructure child, List<EquipmentStructure> structures) {
//        for (EquipmentStructure structure : structures) {
//            if (structure.getID().equals(child.getParentID())) {
//                return structure;
//            }
//        }
//        return null;
//    }

    private void setIndex(List<EquipmentStructure> nodes, String parentIndex) {
        for (int i = 0; i < nodes.size(); i++) {
            EquipmentStructure node = nodes.get(i);
            String currentIndex = parentIndex.isEmpty() ? String.valueOf(i) : parentIndex + "-" + i;
            node.setLevels(currentIndex);
            // 递归调用子节点
            setIndex(node.getChildren(), currentIndex);
        }
    }

    @RequestMapping("/select/EquipmentStructureID/EquipmentBasicInfo")
    @ResponseBody
    public List<EquipmentStructure> selectEquipmentStructureIDEquipmentBasicInfo(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        return equipmentStructureService.selectEquipmentStructureID(id);
    }

}
